'use strict';


const common_channel = "/topic/common/message",
private_channel = "/user/topic/private/message",
room_channel = "/app/topic/room",
transfer_channel = "/app/topic/transfer-msg",
end_point = "./marcopolo",
pcConfig = {
	'iceServers':[{
		'url':'stun:stun.l.google.com:19302'
	}]
}


var pc = new Map(),
	remoteStream = [],
	subscription = null,
	stomp = Stomp.over(new SockJS(end_point)),
	localStream = null;

stomp.connect({},function(frame){
//	console.debug("连接成功");
	//订阅公共信息源
	stomp.subscribe(common_channel,handleCommonMessage);
},function(err){
	console.debug("连接出错",err);
});

function sendMsg(addr,msg){
	stomp.send(addr,{},JSON.stringify({"message":msg}));
}

/**
*信息中转
*/
function transferMsg(msg){
	stomp.send(transfer_channel,{},JSON.stringify({"message":msg}));
}

/**
* 加入房间
*/
function enterRoom(){
	subscription = stomp.subscribe(private_channel,handlePrivateMessage);
	//发送加入房间指令
	stomp.send(room_channel);
}

/**
* 公共信息处理
*/
function handleCommonMessage(message){
	vm.notice.push(message.body);
}

/**
* 私人信息处理
*/
function handlePrivateMessage(message){
	console.log("handlePrivateMessage",message);
	var payload = JSON.parse(message.body);
	switch(payload.cmd){
	case 'myself':
		vm.notice.push("用户编号： "+payload.message);
		break;
	case 'wait':
		alert("当前房间没有人，请稍后")
		vm.notice.push("当前房间没有人，请稍后");
		break;
	case 'join':
		joinRoom(payload.data);
		break;
	case 'full':
		alert("房间已满");
		vm.notice.push("房间已满");
		break;
	case 'end':
		closeWebRTC();
		break;
	case 'offer':
		var sdp = JSON.parse(payload.data);
		reactOffer(payload.caller,sdp);
		break;
	case 'answer':
		var sdp = JSON.parse(payload.data);
		pc.get(payload.caller).setRemoteDescription(new RTCSessionDescription(sdp));
		break;
	case 'candidate':
		var candidate = new RTCIceCandidate(JSON.parse(payload.data));
		pc.get(payload.caller).addIceCandidate(candidate).then(function(e){
			console.debug("成功添加ice candidate",e);
		}).catch(function(e){
			console.debug(e);
		});
		break;
	default:
		console.log("default");
		break;
	}
}

function joinRoom(callee){
	if(localStream != null){
		for(var i = 0;i<callee.length;i++){
			createOffer(callee[i]);
		}
	}else{
		getUM().then(function(){
			for(var i = 0;i<callee.length;i++){
				createOffer(callee[i]);
			}
		});
	}
}

function createOffer(targetCallee){
		var peerConnection = new RTCPeerConnection(pcConfig);
		peerConnection.targetCallee = targetCallee;
		peerConnection.onicecandidate = function(event){
//				console.log("ice candidate事件被触发: ",this.targetCallee);
				if(event.candidate){
					stomp.send(transfer_channel,{},JSON.stringify({"cmd":"candidate","callee":this.targetCallee,"data":JSON.stringify(event.candidate)}));
				}else{
					console.debug("End of candidates.");
				}
		}
		peerConnection.onicecandidatestatechange = onIceStateChange;
		peerConnection.onaddstream = handleRemoteStreamAdded;
		peerConnection.onremovestream = handleRemoteStreamRemoved;
//		peerConnection.ondatachannel = receivehandler;
		
		peerConnection.addStream(localStream);
		peerConnection.createOffer(function(sdp){
			peerConnection.setLocalDescription(sdp);
			stomp.send(transfer_channel,{},JSON.stringify({"cmd":"offer","callee":targetCallee,"data":JSON.stringify(sdp)}));
		}, handleCreateOfferError);
		
		pc.set(targetCallee,peerConnection);
}

function getUM(){
	return new Promise(function(resolve, reject){
		navigator.mediaDevices.getUserMedia({
//			audio:true,
			 video: {
			      /*mandatory: {
			        chromeMediaSource: 'screen'
			        // maxWidth: 640,
			        // maxHeight: 480
			      }*/
//				 meidaSource:'screen',
				 mandatory:{
					 chromeMediaSource:'screen'
				 }
			    }
		}).then(
			function(stream){
//				vm.localVideo = window.URL.createObjectURL(stream);
				localStream = stream;
				resolve();
			},function(err){
				console.debug("获取媒体资源时出错err",err)
		}).catch(function(e){
			console.debug("获取媒体资源时出错e",e);
		});
	});
}

function reactOffer(caller,sdp){
	if(localStream != null){
		createAnswer(caller,sdp);
	}else{
		getUM().then(function(){
			createAnswer(caller,sdp);
		});
	}
}

function createAnswer(caller,sdp){
	var peerConnection = new RTCPeerConnection(pcConfig);
	peerConnection.targetCallee = caller;
	peerConnection.onicecandidate = function(event,caller){
//			console.debug("ice candidate事件被触发: ",event);
			if(event.candidate){
				stomp.send(transfer_channel,{},JSON.stringify({"cmd":"candidate","callee":this.targetCallee,"data":JSON.stringify(event.candidate)}));
			}else{
				console.debug("End of candidates.");
			}
	}
	peerConnection.onicecandidatestatechange = onIceStateChange;
	peerConnection.onaddstream = handleRemoteStreamAdded;
	peerConnection.onremovestream = handleRemoteStreamRemoved;
//	peerConnection.ondatachannel = receivehandler;
	
	
	peerConnection.setRemoteDescription(new RTCSessionDescription(sdp));
	
	peerConnection.addStream(localStream);
	peerConnection.createAnswer().then(function(sdp){
		peerConnection.setLocalDescription(sdp);
		stomp.send(transfer_channel,{},JSON.stringify({"cmd":"answer","callee":caller,"data":JSON.stringify(sdp)}));
	},onCreateSessionDescriptionError);
	
	pc.set(caller,peerConnection);
}

function onIceStateChange(event){
	console.debug("Ice State has change: "+e)
}

function handleRemoteStreamAdded(event){
	vm.remoteVideo.push(window.URL.createObjectURL(event.stream));
//	remoteSrc.push(window.URL.createObjectURL(event.stream));
	remoteStream.push(event.stream);
}

function handleRemoteStreamRemoved(event) {
	  console.debug('Remote stream removed. Event: ', event);
}

function handleCreateOfferError(event){
	console.debug("createOffer() error: ",event);
}

function onCreateSessionDescriptionError(error) {
	  console.debug('Failed to create session description: ' + error.toString());
	}